<?php


namespace app\admin\controller\coupons;


use app\common\controller\Adminbase;
use think\Db;

class Coupons extends Adminbase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit) = $this->buildTableParames();
            $where[] = ['is_del', '=', 0];
            $filter = input('filter');
            if ($filter) {
                $filter = json_decode($filter, true);
                if (isset($filter['name'])) {
                    $where[] = ['name', 'like', '%' . $filter['name'] . '%'];
                }
                if (isset($filter['status'])) {
                    $where[] = ['status', '=', $filter['status']];
                }
                if (isset($filter['id'])) {
                    $where[] = ['id', '=', $filter['id']];
                }
                if (isset($filter['cate_name'])) {
                    $where[] = ['cate_id', '=', $filter['cate_name']];
                }
            }
            $_list = Db::name('coupons')
                ->page($page, $limit)
                ->order('cate_id sort')
                ->order('sort desc')
                ->where($where)
                ->select();
            foreach ($_list as $k => $v) {
                $coupons_info = Db::name('coupons_cate')->find($v['cate_id']);
                $_list[$k]['cate_name'] = $coupons_info['name'];
                $_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $_list[$k]['give_time'] = date('Y-m-d H:i:s', $v['start_time']) . ' -- ' . date('Y-m-d H:i:s', $v['end_time']);
                if ($v['stock_type'] == 1) {
                    $_list[$k]['total_count'] = '不限量';
                }
            }
            $total = Db::name('coupons')->where($where)->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        //优惠券分类
        $coupons_cate_list = Db::name('coupons_cate')->where([
            'is_del' => 0,
        ])->order('sort desc')->select();
        foreach ($coupons_cate_list as $k => $v) {
            $coupons_cate_list1[$v['id']] = $v['name'];
        }
        $this->assign([
            'coupons_cate_list1' => $coupons_cate_list1
        ]);
        return $this->fetch();
    }

    /**
     * 状态
     */
    public function setstate()
    {
        $id = $this->request->param('id/d', 0);

        $status = $this->request->param('value/d');


        if (Db::name('coupons')->where('id', $id)->update(['status' => $status])) {

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //删除
    public function del()
    {
        $ids = $this->request->param('ids/a', null);
        try {
            //软删除
            foreach ($ids as $id) {
                Db::name('coupons')->where('id', $id)->update([
                    'is_del' => 1
                ]);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('删除成功！');
    }

    //增加
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['start_time'] = explode('--', $data['start_time']);
            $insert_data = array(
                'name' => $data['name'],
                'cate_id' => $data['cate_id'],
                'value' => $data['value'],
                'is_limit' => $data['is_limit'],
                'start_time' => strtotime($data['start_time'][0]),
                'end_time' => strtotime($data['start_time'][1]),
                'effect_type' => $data['effect_type'],
                'stock_type' => $data['stock_type'],
                'status' => 1,
                'is_del' => 0,
                'sort' => $data['sort'],
                'fraction' => $data['fraction'],
                'create_time' => time(),
                'desc' => $data['desc'],
            );
            $result = $this->validate($data, 'Coupons.insert');
            if (true !== $result) {
                msg(-1, $result, '');
            }
            if ($insert_data['effect_type'] == 1) {
                if (empty($data['effect_start'])) {
                    $this->error('有效时间不能为空');
                }
                $data['effect_start'] = explode('--', $data['effect_start']);
                $insert_data['effect_start'] = strtotime($data['effect_start'][0]);
                $insert_data['effect_end'] = strtotime($data['effect_start'][1]);
            } else {
                if (empty($data['effect_day'])) {
                    $this->error('有效天数不能为空');
                }
                $insert_data['effect_day'] = $data['effect_day'];
            }
            if ($insert_data['stock_type'] == 1) {
                $insert_data['total_count'] = 0;
            } else {
                if (empty($data['total_count'])) {
                    $this->error('请填写发放数量');
                }
                $insert_data['total_count'] = $data['total_count'];
            }

            if ($data['is_limit']) {
                $insert_data['min_amount'] = $data['min_amount'];
                if ($data['min_amount'] <= $data['value']) {
                    $this->error('最低消费必须大于面值！');
                }
            } else {
                $insert_data['min_amount'] = $data['value'] + 0.01;
            }
            $stmt = Db::name('coupons')->insertGetId($insert_data);
            if ($stmt) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        } else {
            //获取优惠券类型
            $coupon_cate_list = Db::name('coupons_cate')
                ->where([
                    ['is_del', '=', 0],
                    ['id', '<>', 1],
                    ['status', '=', 1]
                ])->order('sort desc')
                ->select();
            $this->assign([
                    'coupon_cate_list' => $coupon_cate_list
                ]
            );
            return $this->fetch();
        }
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->Post();
            $data['start_time'] = explode('--', $data['start_time']);
            $insert_data = array(
                'id' => $data['id'],
                'name' => $data['name'],
                'cate_id' => $data['cate_id'],
                'value' => $data['value'],
                'is_limit' => $data['is_limit'],
                'start_time' => strtotime($data['start_time'][0]),
                'end_time' => strtotime($data['start_time'][1]),
                'effect_type' => $data['effect_type'],
                'stock_type' => $data['stock_type'],
                'fraction' => $data['fraction'],
                'sort' => $data['sort'],
                'desc' => $data['desc'],
            );
            if ($data['id'] == 1) {
                $insert_data['cate_id'] = 1;
            }
            if ($insert_data['effect_type'] == 1) {
                if (empty($data['effect_start'])) {
                    $this->error('有效时间不能为空');
                }
                $data['effect_start'] = explode('--', $data['effect_start']);
                $insert_data['effect_start'] = strtotime($data['effect_start'][0]);
                $insert_data['effect_end'] = strtotime($data['effect_start'][1]);
            } else {
                if (empty($data['effect_day'])) {
                    $this->error('有效天数不能为空');
                }
                $insert_data['effect_day'] = $data['effect_day'];
            }
            if ($insert_data['stock_type'] == 1) {
                $insert_data['total_count'] = 0;
            } else {
                if (empty($data['total_count'])) {
                    $this->error('请填写发放数量');
                }
                $insert_data['total_count'] = $data['total_count'];
            }
            if ($data['is_limit']) {
                $insert_data['min_amount'] = $data['min_amount'];
                if ($data['min_amount'] <= $data['value']) {
                    $this->error('最低消费必须大于面值！');
                }
            } else {
                $insert_data['min_amount'] = $data['value'] + 0.01;
            }
            $stmt = Db::name('coupons')->update($insert_data);
            if ($stmt) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
            return $data;
        }

        $id = $this->request->param('id/d', 0);
        $data = Db::name('coupons')->find($id);
        $coupon_cate_list = Db::name('coupons_cate')
            ->where([
                ['is_del', '=', 0],
                ['id', '<>', 1],
                ['status', '=', 1]
            ])
            ->order('sort desc')
            ->select();

        //领取时间
        $data['start_time'] = date('Y-m-d H:i:s', $data['start_time']) . ' -- ' . date('Y-m-d H:i:s', $data['end_time']);
        //有效时间
        if ($data['effect_type'] == 1) {
            $data['effect_start'] = date('Y-m-d H:i:s', $data['effect_start']) . ' -- ' . date('Y-m-d H:i:s', $data['effect_end']);
        } else {
            $data['effect_start'] = null;
        }
        $this->assign([
                'coupon_cate_list' => $coupon_cate_list,
                'data' => $data
            ]
        );
        return $this->fetch();
    }

    public function sendCoupons(){
        if ($this->request->isPost()) {
            $data = $this->request->Post();
            $member_info=Db::name('member')->find($data['user_id']);
            if (!$member_info){
                $this->error('用户不存在！');
            }
            $coupons_info=Db::name('coupons')->find($data['id']);
            getCoupons($data['user_id'],$coupons_info,4);
            $this->success('操作成功！');
        }
        $id = $this->request->param('id/d', 0);
        $this->assign([
            'id'=>$id
        ]);
        return $this->fetch('send');
    }


}